import type { IAccount } from '@/types'
import type { ILoginState } from './type'
import { postAccountloginApi, getUserMenusByRoleIdApi } from '@/service/api'
import { defineStore } from 'pinia'
import { mapMenusToRoutes } from '@/utils/permission'
import router from '@/router'
import  getMenuList from '@/utils/aysncMenu'
import useCommonStore from '../main/common/common'
import useRouterJump from '@/hooks/useRouterJump'
import { isCode } from '@/utils/iscode'
const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    loginToken: '',
    userMenus: [],
    btnPermissions: []
  }),
  actions: {
    async loginAction(account: IAccount) {
      // 登录
      const loginRes = await postAccountloginApi(account)
      if(isCode(loginRes)){
        this.loginToken = loginRes.result.token
         // 获取角色菜单列表
        const userMenuRes = await getUserMenusByRoleIdApi()
        this.userMenus = getMenuList(userMenuRes.result)
        
        // 将角色菜单列表映射成路由列表，并动态添加路由
        const asyncRoutes = mapMenusToRoutes(this.userMenus)
        asyncRoutes.forEach((route) => router.addRoute('main', route))

        router.push('/main')
      }
    },
    logoutAction() {
      useRouterJump('/login')
      this.$reset()
    },
    // 如果刷新，重新注册路由
    loadLocalCacheAction() {
      if (this.loginToken  && this.userMenus) {
       

        // 重新加载所有角色和部门数据
        // const commonStore = useCommonStore()
        // commonStore.fetchEntireDataAction()

        // 重新动态添加路由
        const asyncRoutes = mapMenusToRoutes(this.userMenus)
        asyncRoutes.forEach((route) => router.addRoute('main', route))
      }
    }
  },
  persist: {
    paths: ['loginToken', 'userMenus', 'btnPermissions']
  }
})

export default useLoginStore
